{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# End-to-End"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-info\">\n",
    "\n",
    "This tutorial is available as an IPython notebook at [Malaya/example/translation](https://github.com/huseinzol05/Malaya/tree/master/example/translation).\n",
    "    \n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-info\">\n",
    "\n",
    "This module trained on both standard and local (included social media) language structures, so it is save to use for both.\n",
    "    \n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = ''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/husein/.local/lib/python3.8/site-packages/bitsandbytes/cextension.py:34: UserWarning: The installed version of bitsandbytes was compiled without GPU support. 8-bit optimizers, 8-bit multiplication, and GPU quantization are unavailable.\n",
      "  warn(\"The installed version of bitsandbytes was compiled without GPU support. \"\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "/home/husein/.local/lib/python3.8/site-packages/bitsandbytes/libbitsandbytes_cpu.so: undefined symbol: cadam32bit_grad_fp32\n",
      "CPU times: user 3.18 s, sys: 2.7 s, total: 5.89 s\n",
      "Wall time: 2.69 s\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/husein/dev/malaya/malaya/tokenizer.py:214: FutureWarning: Possible nested set at position 3397\n",
      "  self.tok = re.compile(r'({})'.format('|'.join(pipeline)))\n",
      "/home/husein/dev/malaya/malaya/tokenizer.py:214: FutureWarning: Possible nested set at position 3927\n",
      "  self.tok = re.compile(r'({})'.format('|'.join(pipeline)))\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "\n",
    "import malaya\n",
    "import logging\n",
    "\n",
    "logging.basicConfig(level=logging.INFO)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### List available HuggingFace models"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'mesolitica/translation-t5-tiny-standard-bahasa-cased': {'Size (MB)': 139,\n",
       "  'Suggested length': 1536,\n",
       "  'en-ms chrF2++': 65.91,\n",
       "  'ms-en chrF2++': 61.3,\n",
       "  'ind-ms chrF2++': 58.15,\n",
       "  'jav-ms chrF2++': 49.33,\n",
       "  'pasar ms-ms chrF2++': 58.46,\n",
       "  'pasar ms-en chrF2++': 55.76,\n",
       "  'manglish-ms chrF2++': 51.04,\n",
       "  'manglish-en chrF2++': 52.2,\n",
       "  'from lang': ['en', 'ms', 'ind', 'jav', 'bjn', 'manglish', 'pasar ms'],\n",
       "  'to lang': ['en', 'ms']},\n",
       " 'mesolitica/translation-t5-small-standard-bahasa-cased': {'Size (MB)': 242,\n",
       "  'Suggested length': 1536,\n",
       "  'en-ms chrF2++': 67.37,\n",
       "  'ms-en chrF2++': 63.79,\n",
       "  'ind-ms chrF2++': 58.09,\n",
       "  'jav-ms chrF2++': 52.11,\n",
       "  'pasar ms-ms chrF2++': 62.49,\n",
       "  'pasar ms-en chrF2++': 60.77,\n",
       "  'manglish-ms chrF2++': 52.84,\n",
       "  'manglish-en chrF2++': 53.65,\n",
       "  'from lang': ['en', 'ms', 'ind', 'jav', 'bjn', 'manglish', 'pasar ms'],\n",
       "  'to lang': ['en', 'ms']},\n",
       " 'mesolitica/translation-t5-base-standard-bahasa-cased': {'Size (MB)': 892,\n",
       "  'Suggested length': 1536,\n",
       "  'en-ms chrF2++': 67.62,\n",
       "  'ms-en chrF2++': 64.41,\n",
       "  'ind-ms chrF2++': 59.25,\n",
       "  'jav-ms chrF2++': 52.86,\n",
       "  'pasar ms-ms chrF2++': 62.99,\n",
       "  'pasar ms-en chrF2++': 62.06,\n",
       "  'manglish-ms chrF2++': 54.4,\n",
       "  'manglish-en chrF2++': 54.14,\n",
       "  'from lang': ['en', 'ms', 'ind', 'jav', 'bjn', 'manglish', 'pasar ms'],\n",
       "  'to lang': ['en', 'ms']},\n",
       " 'mesolitica/translation-t5-small-standard-bahasa-cased-v2': {'Size (MB)': 242,\n",
       "  'Suggested length': 2048,\n",
       "  'en-ms chrF2++': 67.8,\n",
       "  'ms-en chrF2++': 64.53,\n",
       "  'ind-ms chrF2++': 60.38,\n",
       "  'jav-ms chrF2++': 53.48,\n",
       "  'pasar ms-ms chrF2++': 63.13,\n",
       "  'pasar ms-en chrF2++': 63.04,\n",
       "  'manglish-ms chrF2++': 56.57,\n",
       "  'manglish-en chrF2++': 54.14,\n",
       "  'from lang': ['en', 'ms', 'ind', 'jav', 'bjn'],\n",
       "  'to lang': ['en', 'ms']},\n",
       " 'mesolitica/translation-t5-small-standard-bahasa-cased-code': {'Size (MB)': 242,\n",
       "  'Suggested length': 2048,\n",
       "  'en-ms chrF2++': 66.89,\n",
       "  'ms-en chrF2++': 63.79,\n",
       "  'from lang': ['en', 'ms', 'ind', 'jav', 'bjn'],\n",
       "  'to lang': ['en', 'ms']},\n",
       " 'mesolitica/translation-nanot5-tiny-malaysian-cased': {'Size (MB)': 205,\n",
       "  'Suggested length': 2048,\n",
       "  'en-ms chrF2++': 63.61,\n",
       "  'ms-en chrF2++': 59.55,\n",
       "  'ind-ms chrF2++': 56.38,\n",
       "  'jav-ms chrF2++': 47.68,\n",
       "  'mandarin-ms chrF2++': 36.61,\n",
       "  'mandarin-en chrF2++': 39.78,\n",
       "  'pasar ms-ms chrF2++': 58.74,\n",
       "  'pasar ms-en chrF2++': 54.87,\n",
       "  'manglish-ms chrF2++': 50.76,\n",
       "  'manglish-en chrF2++': 53.16,\n",
       "  'from lang': ['en',\n",
       "   'ms',\n",
       "   'ind',\n",
       "   'jav',\n",
       "   'bjn',\n",
       "   'manglish',\n",
       "   'pasar ms',\n",
       "   'mandarin',\n",
       "   'pasar mandarin'],\n",
       "  'to lang': ['en', 'ms']},\n",
       " 'mesolitica/translation-nanot5-small-malaysian-cased': {'Size (MB)': 358,\n",
       "  'Suggested length': 2048,\n",
       "  'en-ms chrF2++': 66.98,\n",
       "  'ms-en chrF2++': 63.52,\n",
       "  'ind-ms chrF2++': 58.1,\n",
       "  'jav-ms chrF2++': 51.55,\n",
       "  'mandarin-ms chrF2++': 46.09,\n",
       "  'mandarin-en chrF2++': 44.13,\n",
       "  'pasar ms-ms chrF2++': 63.2,\n",
       "  'pasar ms-en chrF2++': 59.78,\n",
       "  'manglish-ms chrF2++': 54.09,\n",
       "  'manglish-en chrF2++': 55.27,\n",
       "  'from lang': ['en',\n",
       "   'ms',\n",
       "   'ind',\n",
       "   'jav',\n",
       "   'bjn',\n",
       "   'manglish',\n",
       "   'pasar ms',\n",
       "   'mandarin',\n",
       "   'pasar mandarin'],\n",
       "  'to lang': ['en', 'ms']},\n",
       " 'mesolitica/translation-nanot5-base-malaysian-cased': {'Size (MB)': 990,\n",
       "  'Suggested length': 2048,\n",
       "  'en-ms chrF2++': 67.87,\n",
       "  'ms-en chrF2++': 64.79,\n",
       "  'ind-ms chrF2++': 56.98,\n",
       "  'jav-ms chrF2++': 51.21,\n",
       "  'mandarin-ms chrF2++': 47.39,\n",
       "  'mandarin-en chrF2++': 48.78,\n",
       "  'pasar ms-ms chrF2++': 65.06,\n",
       "  'pasar ms-en chrF2++': 64.03,\n",
       "  'manglish-ms chrF2++': 57.91,\n",
       "  'manglish-en chrF2++': 55.66,\n",
       "  'from lang': ['en',\n",
       "   'ms',\n",
       "   'ind',\n",
       "   'jav',\n",
       "   'bjn',\n",
       "   'manglish',\n",
       "   'pasar ms',\n",
       "   'mandarin',\n",
       "   'pasar mandarin'],\n",
       "  'to lang': ['en', 'ms']}}"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "malaya.translation.available_huggingface"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1. tested on FLORES200 pair `dev` set, https://github.com/huseinzol05/malay-dataset/tree/master/translation/flores200-eval\n",
      "2. tested on noisy test set, https://github.com/huseinzol05/malay-dataset/tree/master/translation/noisy-eval\n",
      "3. check out NLLB 200 metrics from `malaya.translation.nllb_metrics`.\n",
      "4. check out Google Translate metrics from `malaya.translation.google_translate_metrics`.\n"
     ]
    }
   ],
   "source": [
    "print(malaya.translation.info)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Improvements of new model\n",
    "\n",
    "1. able to translate `[en, ms, ind, jav, bjn, manglish, pasar ms, mandarin, pasar mandarin]` while old model only able to translate `[en, ms, pasar ms]`.\n",
    "2. No longer required `from_lang` part of the prefix.\n",
    "3. able to retain text structure as it is."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Load Transformer models\n",
    "\n",
    "```python\n",
    "def huggingface(\n",
    "    model: str = 'mesolitica/translation-t5-small-standard-bahasa-cased',\n",
    "    force_check: bool = True,\n",
    "    from_lang: List[str] = None,\n",
    "    to_lang: List[str] = None,\n",
    "    old_model: bool = False,\n",
    "    **kwargs,\n",
    "):\n",
    "    \"\"\"\n",
    "    Load HuggingFace model to translate.\n",
    "\n",
    "    Parameters\n",
    "    ----------\n",
    "    model: str, optional (default='mesolitica/translation-t5-small-standard-bahasa-cased')\n",
    "        Check available models at `malaya.translation.available_huggingface()`.\n",
    "    force_check: bool, optional (default=True)\n",
    "        Force check model one of malaya model.\n",
    "        Set to False if you have your own huggingface model.\n",
    "\n",
    "    Returns\n",
    "    -------\n",
    "    result: malaya.torch_model.huggingface.Translation\n",
    "    \"\"\"\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "model = malaya.translation.huggingface(model = 'mesolitica/translation-nanot5-small-malaysian-cased')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Translate\n",
    "\n",
    "```python\n",
    "def generate(self, strings: List[str], to_lang: str = 'ms', **kwargs):\n",
    "    \"\"\"\n",
    "    Generate texts from the input.\n",
    "\n",
    "    Parameters\n",
    "    ----------\n",
    "    strings : List[str]\n",
    "    to_lang: str, optional (default='ms')\n",
    "        target language to translate.\n",
    "    **kwargs: vector arguments pass to huggingface `generate` method.\n",
    "        Read more at https://huggingface.co/docs/transformers/main_classes/text_generation\n",
    "\n",
    "        If you are using `use_ctranslate2`, vector arguments pass to ctranslate2 `translate_batch` method.\n",
    "        Read more at https://opennmt.net/CTranslate2/python/ctranslate2.Translator.html?highlight=translate_batch#ctranslate2.Translator.translate_batch\n",
    "\n",
    "    Returns\n",
    "    -------\n",
    "    result: List[str]\n",
    "    \"\"\"\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pprint import pprint"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('TANGKAK - Tan Sri Muhyiddin Yassin berkata, beliau tidak mahu menyentuh '\n",
      " 'mengenai isu politik buat masa ini, sebaliknya mahu menumpukan kepada soal '\n",
      " 'kebajikan rakyat serta usaha merancakkan semula ekonomi negara yang terjejas '\n",
      " 'berikutan pandemik Covid-19. Perdana Menteri menjelaskan perkara itu ketika '\n",
      " 'berucap pada Majlis Bertemu Pemimpin bersama pemimpin masyarakat Dewan '\n",
      " 'Undangan Negeri (DUN) Gambir di Dewan Serbaguna Bukit Gambir hari ini.')\n"
     ]
    }
   ],
   "source": [
    "# https://www.sinarharian.com.my/article/89678/BERITA/Politik/Saya-tidak-mahu-sentuh-isu-politik-Muhyiddin\n",
    "\n",
    "string_news1 = 'TANGKAK - Tan Sri Muhyiddin Yassin berkata, beliau tidak mahu menyentuh mengenai isu politik buat masa ini, sebaliknya mahu menumpukan kepada soal kebajikan rakyat serta usaha merancakkan semula ekonomi negara yang terjejas berikutan pandemik Covid-19. Perdana Menteri menjelaskan perkara itu ketika berucap pada Majlis Bertemu Pemimpin bersama pemimpin masyarakat Dewan Undangan Negeri (DUN) Gambir di Dewan Serbaguna Bukit Gambir hari ini.'\n",
    "pprint(string_news1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('ALOR SETAR - Kemelut politik Pakatan Harapan (PH) belum berkesudahan apabila '\n",
      " 'masih gagal memuktamadkan calon Perdana Menteri yang dipersetujui bersama. '\n",
      " 'Ahli Parlimen Sik, Ahmad Tarmizi Sulaiman berkata, sehubungan itu pihaknya '\n",
      " 'mencadangkan mantan Pengerusi Parti Pribumi Bersatu Malaysia (Bersatu), Tun '\n",
      " 'Dr Mahathir Mohamad dan Presiden Parti Keadilan Rakyat (PKR), Datuk Seri '\n",
      " 'Anwar Ibrahim mengundurkan diri daripada politik sebagai jalan penyelesaian.')\n"
     ]
    }
   ],
   "source": [
    "# https://www.sinarharian.com.my/article/90021/BERITA/Politik/Tun-Mahathir-Anwar-disaran-bersara-untuk-selesai-kemelut-politik\n",
    "\n",
    "string_news2 = 'ALOR SETAR - Kemelut politik Pakatan Harapan (PH) belum berkesudahan apabila masih gagal memuktamadkan calon Perdana Menteri yang dipersetujui bersama. Ahli Parlimen Sik, Ahmad Tarmizi Sulaiman berkata, sehubungan itu pihaknya mencadangkan mantan Pengerusi Parti Pribumi Bersatu Malaysia (Bersatu), Tun Dr Mahathir Mohamad dan Presiden Parti Keadilan Rakyat (PKR), Datuk Seri Anwar Ibrahim mengundurkan diri daripada politik sebagai jalan penyelesaian.'\n",
    "pprint(string_news2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('Menteri Kanan (Kluster Keselamatan) Datuk Seri Ismail Sabri Yaakob berkata, '\n",
      " 'kelonggaran itu diberi berikutan kerajaan menyedari masalah yang dihadapi '\n",
      " 'mereka untuk memperbaharui dokumen itu. Katanya, selain itu, bagi rakyat '\n",
      " 'asing yang pas lawatan sosial tamat semasa Perintah Kawalan Pergerakan (PKP) '\n",
      " 'pula boleh ke pejabat Jabatan Imigresen yang terdekat untuk mendapatkan '\n",
      " 'lanjutan tempoh.')\n"
     ]
    }
   ],
   "source": [
    "string_news3 = 'Menteri Kanan (Kluster Keselamatan) Datuk Seri Ismail Sabri Yaakob berkata, kelonggaran itu diberi berikutan kerajaan menyedari masalah yang dihadapi mereka untuk memperbaharui dokumen itu. Katanya, selain itu, bagi rakyat asing yang pas lawatan sosial tamat semasa Perintah Kawalan Pergerakan (PKP) pula boleh ke pejabat Jabatan Imigresen yang terdekat untuk mendapatkan lanjutan tempoh.'\n",
    "pprint(string_news3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('Selain itu, pameran kerjaya membantu para pelajar menentukan kerjaya yang '\n",
      " 'akan diceburi oleh mereka. Seperti yang kita ketahui, pasaran kerjaya di '\n",
      " 'Malaysia sangat luas dan masih banyak sektor pekerjaan di negara ini yang '\n",
      " 'masih kosong kerana sukar untuk mencari tenaga kerja yang benar-benar '\n",
      " 'berkelayakan. Sebagai contohnya, sektor perubatan di Malaysia menghadapi '\n",
      " 'masalah kekurangan tenaga kerja yang kritikal, khususnya tenaga pakar '\n",
      " 'disebabkan peletakan jawatan oleh doktor dan pakar perubatan untuk memasuki '\n",
      " 'sektor swasta serta berkembangnya perkhidmatan kesihatan dan perubatan. '\n",
      " 'Setelah menyedari  hakikat ini, para pelajar akan lebih berminat untuk '\n",
      " 'menceburi bidang perubatan kerana pameran kerjaya yang dilaksanakan amat '\n",
      " 'membantu memberikan pengetahuan am tentang kerjaya ini')\n"
     ]
    }
   ],
   "source": [
    "# https://qcikgubm.blogspot.com/2018/02/contoh-soalan-dan-jawapan-karangan.html\n",
    "\n",
    "string_karangan = 'Selain itu, pameran kerjaya membantu para pelajar menentukan kerjaya yang akan diceburi oleh mereka. Seperti yang kita ketahui, pasaran kerjaya di Malaysia sangat luas dan masih banyak sektor pekerjaan di negara ini yang masih kosong kerana sukar untuk mencari tenaga kerja yang benar-benar berkelayakan. Sebagai contohnya, sektor perubatan di Malaysia menghadapi masalah kekurangan tenaga kerja yang kritikal, khususnya tenaga pakar disebabkan peletakan jawatan oleh doktor dan pakar perubatan untuk memasuki sektor swasta serta berkembangnya perkhidmatan kesihatan dan perubatan. Setelah menyedari  hakikat ini, para pelajar akan lebih berminat untuk menceburi bidang perubatan kerana pameran kerjaya yang dilaksanakan amat membantu memberikan pengetahuan am tentang kerjaya ini'\n",
    "pprint(string_karangan)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['TANGKAK - Tan Sri Muhyiddin Yassin said he does not want to touch on '\n",
      " 'political issues for now, but instead wants to focus on the welfare of the '\n",
      " \"people and efforts to revitalize the country's economy which has been \"\n",
      " 'affected due to the Covid-19 pandemic. The Prime Minister explained the '\n",
      " 'matter when speaking at the Meeting of Leaders with community leaders of the '\n",
      " 'Gambir State Legislative Assembly at the Bukit Gambir Multipurpose Hall '\n",
      " 'today.',\n",
      " 'ALOR SETAR - The Pakatan Harapan (PH) political turmoil has not ended when '\n",
      " 'it still failed to finalize the candidate for Prime Minister agreed upon. '\n",
      " 'Sik Member of Parliament, Ahmad Tarmizi Sulaiman said, in that regard, he '\n",
      " 'proposed that former Chairman of Parti Pribumi Bersatu Malaysia (Bersatu), '\n",
      " 'Tun Dr Mahathir Mohamad and Parti Keadilan Rakyat (PKR) President, Datuk '\n",
      " 'Seri Anwar Ibrahim to withdraw from politics as a solution.',\n",
      " 'Senior Minister (Security Cluster) Datuk Seri Ismail Sabri Yaakob said that '\n",
      " \"the relaxation was given following the government's concern to renew the \"\n",
      " 'document. He said, in addition, for foreigners whose social visit pass '\n",
      " 'expires during the Movement Control Order (MCO) can go to the nearest '\n",
      " 'Immigration Department office to obtain an extension of the period.',\n",
      " 'Furthermore, career exhibitions help students determine the career that they '\n",
      " 'will pursue. As we know, the career market in Malaysia is vast and there are '\n",
      " 'still many job sectors in the country that are still vacant due to the '\n",
      " 'difficulty in finding a truly qualified workforce. For example, the medical '\n",
      " 'sector in Malaysia is facing a critical shortage of workforce, especially '\n",
      " 'specialist staff due to the resignation of doctors and medical experts to '\n",
      " 'enter the private sector and the development of health and medical services. '\n",
      " 'After realizing this fact, students will be more interested in pursuing a '\n",
      " 'career in the field of medicine as the career exhibitions carried out '\n",
      " 'greatly help provide general knowledge about this career.']\n",
      "CPU times: user 3min 5s, sys: 2.44 s, total: 3min 8s\n",
      "Wall time: 17 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "\n",
    "pprint(model.generate([string_news1, string_news2, string_news3, string_karangan], \n",
    "                      to_lang = 'en', max_length = 1000))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Able to translate code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "`Untuk menggunakan numpy, pertama, anda perlu memasangnya melalui pip. Anda boleh lakukannya dengan menjalankan perintah `pip install numpy` di terminal anda.\n",
      "Selepas numpy dipasang, anda boleh import modul numpy dengan menambah baris `import numpy as np` pada permulaan program anda.\n",
      "Berikut adalah contoh beberapa operasi asas numpy:\n",
      "``` python\n",
      "import numpy as np\n",
      "# buat array numpy dari senarai\n",
      "my_list = [1, 2, 3, 4, 5]\n",
      "my_array = np.array(my_list)\n",
      "# buat array numpy dengan julat nilai tertentu\n",
      "my_range = np.arange(0, 10, 2) # nilai awal, nilai akhir, dan lompatan\n",
      "# buat array numpy dengan nilai rawak\n",
      "my_random_array = np.random.rand(3, 3) # 3 baris dan 3 lajur\n",
      "# akses elemen array numpy\n",
      "print(my_array[0]) # akses elemen pertama\n",
      "# lakukan operasi matematik pada array numpy\n",
      "my_array = my_array + 1 # tambah setiap elemen dengan 1\n",
      "my_array = my_array * 2 # darab setiap elemen dengan 2\n",
      "# ubah bentuk array numpy\n",
      "my_array = np.reshape(my_array, (2, 5)) # menjadi array 2D dengan 2 baris dan 5 lajur\n",
      "```\n",
      "Itulah beberapa operasi asas numpy. Anda boleh cari dokumentasi rasmi numpy di https://numpy.org/doc/stable/.\n"
     ]
    }
   ],
   "source": [
    "s = \"\"\"\n",
    "`Untuk menggunakan numpy, pertama, Anda perlu menginstalnya melalui pip. Anda dapat melakukannya dengan menjalankan perintah `pip install numpy` di terminal Anda.\n",
    "Setelah numpy terinstal, Anda dapat mengimpor modul numpy dengan menambahkan baris `import numpy as np` di awal program Anda.\n",
    "Berikut adalah contoh beberapa operasi dasar numpy:\n",
    "``` python\n",
    "import numpy as np\n",
    "# membuat array numpy dari list\n",
    "my_list = [1, 2, 3, 4, 5]\n",
    "my_array = np.array(my_list)\n",
    "# membuat array numpy dengan rentang nilai tertentu\n",
    "my_range = np.arange(0, 10, 2) # nilai awal, nilai akhir, dan loncatan\n",
    "# membuat array numpy dengan nilai acak\n",
    "my_random_array = np.random.rand(3, 3) # 3 baris dan 3 kolom\n",
    "# mengakses elemen array numpy\n",
    "print(my_array[0]) # mengakses elemen pertama\n",
    "# melakukan operasi matematika pada array numpy\n",
    "my_array = my_array + 1 # menambah setiap elemen dengan 1\n",
    "my_array = my_array * 2 # mengalikan setiap elemen dengan 2\n",
    "# mengubah bentuk array numpy\n",
    "my_array = np.reshape(my_array, (2, 5)) # menjadi array 2D dengan 2 baris dan 5 kolom\n",
    "```\n",
    "Itulah beberapa operasi dasar numpy. Anda dapat menemukan dokumentasi resmi numpy di https://numpy.org/doc/stable/.\n",
    "\"\"\"\n",
    "\n",
    "print(model.generate([s], to_lang = 'ms', max_length = 1000)[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Able to maintain input structure"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "26 DR. 27.10.2021\n",
      "\n",
      " \n",
      "MOTION TO ADJOURN THE MEETING\n",
      "\n",
      "UNDER P.M. 18(1)\n",
      " \n",
      "\n",
      "PETRONAS GAS ASSET SALE IN AZERBAIJAN\n",
      "\n",
      " \n",
      "\n",
      "11.33 a.m.\n",
      "\n",
      "Dato' Seri Anwar bin Ibrahim [Port Dickson]: Mr. Speaker, I am\n",
      "please submit a motion under Meeting Rules 18(1) and 18(2) Regulations-\n",
      " Rules of the Dewan Rakyat Meeting as follows:\n",
      "\n",
      "\"That the House in session today negotiated\n",
      "report that Petronas has sold gas assets in Azerbaijan with\n",
      "price almost RM10 billion following the government's insistence on raising\n",
      "Petronas dividend payment of RM25 billion to the government for\n",
      "year 2021.”\n",
      "\n",
      " \n",
      "This is a certain matter because of the sale of gas assets in Azerbaijan\n",
      "\n",
      "worth RM10 billion and also dividend payments to the government amounting to RM25 billion\n",
      "for 2021 is dangerous and affects Petronas' future. Related\n",
      "with a little explanation. Because actions like this have caused J.P. Morgan\n",
      "issued Petronas from ESG Emerging Market Bond Index and ESG Asia Credit\n",
      "Index.\n",
      "\n",
      "Therefore, the matter needs to be expedited because Petronas is experiencing a deficit\n",
      "following excessive dividend payments since 2018 until now that are forced\n",
      "Petronas sells assets or borrows more foreign funds to cover\n",
      "cash flow.\n",
      "\n",
      "This is reinforced by the statement of Tengku Muhammad Taufik, CEO of Petronas, \"If\n",
      "there is a policy shift but it comes too suddenly or too slowly, not only Petronas but the\n",
      "entire Malaysian economy could be put at risk, with regards to our energy mix.”\n",
      "\n",
      "This is related to the interests of the public, even the rest of the economy\n",
      "country, because Petronas is an important institution of the country's economy and accordingly\n",
      "strengthened its strength and not weakened by the company's rating. Ability to\n",
      "invest to generate future profits that are able to pay dividends\n",
      "which is reasonable to the government for the benefit of the people. With an additional RM7\n",
      "billion this year, Petronas' revenue will amount to RM44.8 billion or 18 percent of\n",
      "government revenue for 2021 from RM37.8 billion previously.\n",
      "\n",
      "So, please get the President's approval to be debated. [Applause]\n",
      "\n",
      "Mr. Speaker: Thank you, Your Honor. Actually Yang\n",
      "Honorable to complete the honorable text and only read the text\n",
      "according to the rules. However, it's okay.\n",
      "\n",
      "Honorable members, I have received a notice of the motion below\n",
      "Meeting Rule 18(1) by Yang Berhormat Port Dickson, Leader of the Opposition on\n",
      "Monday, October 25, 2021. The text of the motion is as read earlier with\n",
      "a little extra by the Honorable Member of Port Dickson just now.\n",
      "\n",
      "To allow this matter to be considered by the Council of Ministers, I\n",
      "should be satisfied that the matter raised by the Honorable\n",
      "comply with three conditions as usual, namely:\n",
      "\n",
      "(i) certain things;\n",
      "\n",
      "(ii) for the interests of the public; and\n",
      "\n",
      "(iii) want to be expedited.\n"
     ]
    }
   ],
   "source": [
    "s = \"\"\"\n",
    "\\n26 DR.27.10.2021 \\n\\n \\nUSUL MENANGGUHKAN MESYUARAT  \\n\\nDI BAWAH P.M. 18(1) \\n \\n\\nPENJUALAN ASET GAS PETRONAS DI AZERBAIJAN \\n\\n \\n\\n11.33 pg. \\n\\nDato’ Seri Anwar bin Ibrahim [Port Dickson]: Tuan Yang di-Pertua, saya \\nmohon mengemukakan usul di bawah Peraturan Mesyuarat 18(1) dan 18(2) Peraturan-\\nperaturan Majlis Mesyuarat Dewan Rakyat seperti berikut: \\n\\n“Bahawa Dewan yang bersidang pada hari ini merundingkan \\nlaporan bahawa Petronas telah menjual aset gas di Azerbaijan dengan \\nharga hampir RM10 bilion berikutan desakan kerajaan menaikkan \\nbayaran dividen Petronas sebanyak RM25 bilion kepada kerajaan bagi \\ntahun 2021.” \\n\\n \\nPerkara ini adalah perkara tertentu kerana penjualan aset gas di Azerbaijan \\n\\nbernilai RM10 bilion dan juga pembayaran dividen kepada kerajaan sebanyak RM25 bilion \\nbagi tahun 2021 adalah berbahaya dan menjejaskan masa depan Petronas. Terkait \\ndengan― sedikit penjelasan.  Kerana tindakan seperti ini telah menyebabkan J.P. Morgan \\nmengeluarkan Petronas dari ESG Emerging Market Bond Index dan ESG Asia Credit \\nIndex.  \\n\\nOleh itu, perkara itu perlu disegerakan kerana Petronas mengalami defisit \\nberikutan pembayaran dividen berlebihan sejak tahun 2018 sehingga kini yang memaksa \\nPetronas menjual aset atau meminjam lebih banyak dana luar negara bagi menampung \\naliran tunai.   \\n\\nIni diperkukuh dengan kenyataan Tengku Muhammad Taufik, CEO Petronas, “If \\nthere is a policy shift but it comes too suddenly or too slowly, not only Petronas but the \\nentire Malaysian economy could be put at risk, with regards to our energy mix.” \\n\\nIni perkara berkenaan dengan kepentingan orang ramai, malah seluruh ekonomi \\nnegara, kerana Petronas adalah institusi penting ekonomi negara dan sewajarnya \\ndiperkukuh kekuatannya dan tidak dilemahkan penarafan syarikat. Kemampuan untuk \\nmelabur bagi menjana keuntungan masa depan yang mampu untuk membayar dividen \\nyang munasabah kepada kerajaan demi kepentingan rakyat. Dengan tambahan RM7 \\nbilion tahun ini, hasil Petronas akan berjumlah RM44.8 bilion atau 18 peratus daripada \\npendapatan kerajaan bagi tahun 2021 daripada RM37.8 bilion sebelumnya. \\n\\nJadi, mohon persetujuan Tuan Yang di-Pertua untuk dibahaskan. [Tepuk] \\n\\nTuan Yang di-Pertua: Terima kasih Yang Berhormat. Sebenarnya Yang \\nBerhormat perlu melengkapkan teks Yang Berhormat dan cuma dibaca teks tersebut \\nmengikut peraturan. Akan tetapi, tak apa.  \\n\\nAhli-ahli Yang Berhormat, saya telah menerima satu pemberitahu usul di bawah \\nPeraturan Mesyuarat 18(1) oleh Yang Berhormat Port Dickson, Ketua Pembangkang pada \\nhari Isnin, 25 Oktober 2021. Teks usul itu adalah seperti yang dibacakan tadi dengan \\nsedikit tambahan oleh Ahli Yang Berhormat Port Dickson sebentar tadi.  \\n\\nBagi membolehkan perkara ini ditimbangkan oleh Majlis Mesyuarat, saya \\nhendaklah berpuas hati bahawa perkara yang dibangkitkan oleh Yang Berhormat itu \\nmematuhi tiga syarat seperti mana biasalah iaitu: \\n\\n(i) perkara tertentu; \\n\\n(ii) bagi kepentingan orang ramai; dan \\n\\n(iii) berkehendak disegerakan. \\n\\n\\n\n",
    "\"\"\"\n",
    "print(model.generate([s], to_lang = 'en', max_length = 1000)[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Able to translate indonesian, banjarese and javanese"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "s1 = 'Kita ora duwe wektu kanggo gelut utawa sengit.'\n",
    "s2 = 'Tiga dekade kemudian area sekolah diperluas.'\n",
    "s3 = 'Maklum haja lah muntung guri wadi kawa haja dipisiti, amun muntung manusia siapang nang hingkat manduga.'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[\"We don't have time to fight or be fierce.\",\n",
      " 'Three decades later the school area was expanded.',\n",
      " \"It's understandable that the people are not ready to be in a bad mood, but \"\n",
      " 'the people are not ready to be in a bad mood.']\n"
     ]
    }
   ],
   "source": [
    "pprint(model.generate([s1, s2, s3], to_lang = 'en', max_length = 1000))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Kita tidak sempat untuk bertarung atau membenci.',\n",
      " 'Tiga dekad kemudian kawasan sekolah telah diperluaskan.',\n",
      " '\"Anda tahu bahawa anda hanya perlu memikirkan perkara yang tidak perlu, '\n",
      " 'tetapi jika anda tidak mahu orang lain yang tidak tahu apa yang perlu '\n",
      " 'dilakukan.\"']\n"
     ]
    }
   ],
   "source": [
    "pprint(model.generate([s1, s2, s3], to_lang = 'ms', max_length = 1000))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Noisy malay"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "strings = [\n",
    "    'ak tak paham la',\n",
    "    'Hi guys! I noticed semalam & harini dah ramai yang dapat cookies ni kan. So harini i nak share some post mortem of our first batch:',\n",
    "    \"Memanglah. Ini tak payah expert, aku pun tau. It's a gesture, bodoh.\",\n",
    "    'jam 8 di pasar KK memang org ramai 😂, pandai dia pilih tmpt.',\n",
    "    'Jadi haram jadah😀😃🤭',\n",
    "    'nak gi mana tuu',\n",
    "    'Macam nak ambil half day',\n",
    "    \"Bayangkan PH dan menang pru-14. Pastu macam-macam pintu belakang ada. Last-last Ismail Sabri naik. That's why I don't give a fk about politics anymore. Sumpah dah fk up dah.\",\n",
    "    'mesolitica boleh buat asr tak',\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Saya tidak faham',\n",
      " 'Hi guys! Saya perasan semalam dan hari ini ramai yang dapat cookies ni kan. '\n",
      " 'Jadi hari ini saya ingin berkongsi beberapa post mortem dari batch pertama '\n",
      " 'kami:',\n",
      " 'Memanglah. Ini tidak perlu pakar, saya juga tahu. Ini adalah isyarat, bodoh.',\n",
      " 'Jam 8 di pasar KK memang ramai orang 😂, pandai dia pilih tempat.',\n",
      " 'Jadi haram jadah 😀😃🤭',\n",
      " 'Ke mana kamu pergi?',\n",
      " 'Saya ingin mengambil separuh hari',\n",
      " 'Bayangkan PH dan menang dalam PRU-14. Kemudian terdapat pelbagai pintu '\n",
      " 'belakang. Akhirnya, Ismail Sabri naik. Itulah sebabnya saya tidak lagi '\n",
      " 'peduli tentang politik. Saya bersumpah saya sudah pergi.',\n",
      " 'Bolehkah mesolitica digunakan untuk membuat asr?']\n",
      "CPU times: user 50.4 s, sys: 48.9 ms, total: 50.4 s\n",
      "Wall time: 4.84 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "\n",
    "pprint(model.generate(strings, to_lang = 'ms', max_length = 1000))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[\"I don't understand\",\n",
      " 'Hi guys! I noticed that many people have received cookies yesterday and '\n",
      " 'today. So today I want to share some post mortem of our first batch:',\n",
      " \"Indeed. No need for an expert, I know. It's a gesture, stupid.\",\n",
      " \"At 8 o'clock in the KK market, it's crowded 😂, he's clever in choosing a \"\n",
      " 'place.',\n",
      " \"So it's illegal😀😃🤭\",\n",
      " 'Where are you going?',\n",
      " 'How to take half a day',\n",
      " 'Imagine PH and winning the 14th general election. Then there are all sorts '\n",
      " \"of backgazes. In the end, Ismail Sabri got in. That's why I don't care about \"\n",
      " \"politics anymore. I swear I'm already fucked up.\",\n",
      " 'Can the mesolitica make Asr?']\n",
      "CPU times: user 1min 26s, sys: 267 ms, total: 1min 27s\n",
      "Wall time: 8.38 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "\n",
    "pprint(model.generate(strings, to_lang = 'en', max_length = 1000))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Manglish"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "strings = [\n",
    "    'i know plenty of people who snack on sambal ikan bilis.',\n",
    "    'I often visualize my own programs algorithm before implemment it.',\n",
    "    'Am I the only one who used their given name ever since I was a kid?',\n",
    "    'Gotta be wary of pimples. Oh they bleed bad when cut',\n",
    "    'Smh the dude literally has a rubbish bin infront of his house',\n",
    "    \"I think I won't be able to catch it within 1 min lol\"\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Saya kenal ramai orang yang makan sambal ikan bilis.',\n",
      " 'Saya sering memvisualisasikan algoritma program saya sendiri sebelum '\n",
      " 'mengimplemmennya.',\n",
      " 'Adakah saya seorang sahaja yang menggunakan nama mereka sejak saya masih '\n",
      " 'kecil?',\n",
      " 'Kena berhati-hati dengan jerawat. Oh, mereka berdarah teruk apabila dipotong',\n",
      " 'Sial, lelaki itu benar-benar mempunyai tong sampah di depan rumahnya.',\n",
      " 'Saya rasa saya tidak akan dapat menangkapnya dalam masa 1 minit lol']\n",
      "CPU times: user 9.66 s, sys: 4.09 ms, total: 9.66 s\n",
      "Wall time: 883 ms\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "\n",
    "pprint(model.generate(strings, to_lang = 'ms', max_length = 1000))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Able to translate Mandarin and local Mandarin"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "s1 = \"\"\"\n",
    "2023年了，依然还存在有很多封建的父母。来聊聊你所遇到的 奇奇怪怪的限制\n",
    "以及 男与女不同对待 程度\n",
    "\n",
    "已嫁女儿 不能回娘家吃团圆饭，不可以拜天公，不可以扫墓\n",
    "红包 外孙 内孙 数目不一\n",
    "可是 有事情，都是找女儿\n",
    "\"\"\"\n",
    "s2 = \"\"\"\n",
    "在選購外套時，防水功能成為了許多人關注的重點之一。極度乾燥外套以其卓越的防水性能和時尚設計，成為了眾多顧客的首選。讓我們來探討一下 極度乾燥 外套的防水技術，以及如何確保你在任何天氣下都能保持乾爽舒適。\n",
    "Superdry 外套 防水高效的防水技術\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[\"It has been 2023, and there are still many principled parents. Let's chat \"\n",
      " 'about the strange restrictions you encountered, and the level of treatment '\n",
      " 'between men and women. If you marry your daughter, you cannot go back to the '\n",
      " \"mother's house for a round trip, you cannot worship the gods, you cannot \"\n",
      " 'clean up the grave. The red envelope, the outside grandson, and the inner '\n",
      " 'grandson, are not the same. However, when there is something, you can always '\n",
      " 'look for your daughter.',\n",
      " 'When choosing a pair of shoes, waterproofing is one of the focus of many '\n",
      " 'people. The highly selesa air conditioning shoes are a popular choice for '\n",
      " \"many customers. Let's explore the highly selesa waterproofing and \"\n",
      " 'waterproofing technology for the highly selesa waterproofing and safety of '\n",
      " 'your shoes. Superdry is a high-quality waterproofing and waterproofing '\n",
      " 'technology.']\n"
     ]
    }
   ],
   "source": [
    "pprint(model.generate([s1, s2], to_lang = 'en', max_length = 1000))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Sejak tahun 2023, masih banyak ibu bapa yang berdedikasi. Mari kita '\n",
      " 'berbincang tentang batasan aneh yang anda hadapi dan tahap perlakuan yang '\n",
      " 'berbeza antara lelaki dan perempuan.\\n'\n",
      " '\\n'\n",
      " 'Sudah berkahwin dengan anak perempuan, tidak boleh pulang ke rumah ibu untuk '\n",
      " 'makan jamuan, tidak boleh menyembah tuhan, tidak boleh menyapu kubur, dan '\n",
      " 'tidak boleh menyapu kubur.\\n'\n",
      " '\\n'\n",
      " 'Bungkusan merah, anak luar, anak luar, jumlah tidak sama.\\n'\n",
      " '\\n'\n",
      " 'Tetapi jika ada sesuatu, semuanya akan mencari anak perempuan.',\n",
      " 'Apabila memilih jaket, fungsi pertahanan air menjadi salah satu fokus utama '\n",
      " 'ramai orang. Jaket yang sangat menyejukkan dengan prestasi dan penampilan '\n",
      " 'yang cemerlang dalam pertahanan air, menjadi pilihan utama ramai pelanggan. '\n",
      " 'Mari kita kunjungi teknologi pertahanan air yang sangat menyejukkan dan '\n",
      " 'memastikan anda sentiasa selesa dan selesa di mana-mana cuaca. Jaket Super '\n",
      " 'Dry teknologi pertahanan air yang cekap.']\n"
     ]
    }
   ],
   "source": [
    "pprint(model.generate([s1, s2], to_lang = 'ms', max_length = 1000))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
